package com.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.myprojectoffeixue.AESUtil;
import com.example.myprojectoffeixue.GateWay;
import com.example.myprojectoffeixue.HttpConnection;
import com.example.myprojectoffeixue.MyApplication;
import com.example.myprojectoffeixue.R;
import com.example.myprojectoffeixue.UserClass;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.task.EsptouchTask;
import com.task.IEsptouchListener;
import com.task.IEsptouchResult;
import com.task.IEsptouchTask;
import com.util.ToastUtils;
import com.util.WifiUtil;

import org.apache.http.entity.StringEntity;

import java.io.UnsupportedEncodingException;
import java.util.List;
public class WifiConfigActivity extends Activity {
	public TextView mTvApSsid;
	private EditText mEdtApPassword;
	private LinearLayout mBtnConfirm;
	public WifiUtil mWifiAdmin;
	MyApplication m;
	private ProgressDialog mProgressDialog;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wificonfig);
		 m= (MyApplication) getApplicationContext();
		mWifiAdmin = new WifiUtil(this);
		mTvApSsid = (TextView) findViewById(R.id.tvApSssidConnected);
		mEdtApPassword = (EditText) findViewById(R.id.edtApPassword);
		/*IntentFilter filter = new IntentFilter();
		filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(new WifiReceiver(), filter);*/
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 获取连接wifi的ssid
		String apSsid = mWifiAdmin.getWifiConnectedSsid();
		if (apSsid != null) {
			mTvApSsid.setText(apSsid);
		} else {
			mTvApSsid.setText("");
		}
		// check whether the wifi is connected
		boolean isApSsidEmpty = TextUtils.isEmpty(apSsid);
		ImageView iv_finish= (ImageView) findViewById(R.id.comm_back);
		LinearLayout iv2= (LinearLayout) findViewById(R.id.btn_confirm);
		iv_finish.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		iv2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				btnConfirm();
			}
		});
//		mBtnConfirm.setEnabled(!isApSsidEmpty);
	}


    public  void btnConfirm() {
        String apSsid = mTvApSsid.getText().toString();
        if(TextUtils.isEmpty(apSsid)){
            ToastUtils.with(this).show("请连接需要配置的WIFI!");
            return;
        }
        String apPassword = mEdtApPassword.getText().toString();
        String apBssid = mWifiAdmin.getWifiConnectedBssid();
        String isSsidHiddenStr = "NO";
        String taskResultCountStr = "1";
        new EsptouchAsyncTask3().execute(apSsid, apBssid, apPassword, isSsidHiddenStr, taskResultCountStr);
    }
	
	private void onEsptoucResultAddedPerform(final IEsptouchResult result) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
//				String text = result.getBssid() + " is connected to the wifi";
//				Toast.makeText(WifiConfigActivity.this, text,
//						Toast.LENGTH_LONG).show();
			}


		});
	}

	private IEsptouchListener myListener =

			new IEsptouchListener() {

		@Override
		public void onEsptouchResultAdded(final IEsptouchResult result) {
			onEsptoucResultAddedPerform(result);
		}
	};
	
	private class EsptouchAsyncTask3 extends AsyncTask<String, Void, List<IEsptouchResult>> {



		private IEsptouchTask mEsptouchTask;
		// without the lock, if the user tap confirm and cancel quickly enough,
		// the bug will arise. the reason is follows:
		// 0. task is starting created, but not finished
		// 1. the task is cancel for the task hasn't been created, it do nothing
		// 2. task is created
		// 3. Oops, the task should be cancelled, but it is running
		private final Object mLock = new Object();

		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(WifiConfigActivity.this);
			mProgressDialog.setMessage("正在配置WLAN,请稍后...");
			mProgressDialog.setCanceledOnTouchOutside(false);
			mProgressDialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					synchronized (mLock) {
						if (mEsptouchTask != null) {
							mEsptouchTask.interrupt();
						}
					}
				}
			});
			mProgressDialog.setButton(DialogInterface.BUTTON_POSITIVE,
					"请稍后...", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			mProgressDialog.show();
			mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE)
					.setEnabled(false);
		}

		@Override
		protected List<IEsptouchResult> doInBackground(String... params) {
			int taskResultCount = -1;
			synchronized (mLock) {
				String apSsid = params[0];
				String apBssid = params[1];
				String apPassword = params[2];
				String isSsidHiddenStr = params[3];
				String taskResultCountStr = params[4];

				boolean isSsidHidden = false;
				if (isSsidHiddenStr.equals("YES")) {
					isSsidHidden = true;
				}
				taskResultCount = Integer.parseInt(taskResultCountStr);
				mEsptouchTask = new EsptouchTask(apSsid, apBssid, apPassword,isSsidHidden, WifiConfigActivity.this);
				mEsptouchTask.setEsptouchListener(myListener);
			}
			List<IEsptouchResult> resultList = mEsptouchTask.executeForResults(taskResultCount);
			return resultList;
		}

		@Override
		protected void onPostExecute(List<IEsptouchResult> result) {

			mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(true);
			mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE).setText("确定");
			IEsptouchResult firstResult = result.get(0);
			// check whether the task is cancelled and no results received
			if (!firstResult.isCancelled()) {
				if (firstResult.isSuc()) {
					m.mac_user= firstResult.getBssid();
					addwg();
				} else {
					mProgressDialog.setMessage("配置失败，请重试");
				}
			}
		}
	}
	public void addwg() {
		if (m.mac_user != null) {
			String mac = m.mac_user.toUpperCase();
			String name = "智能网关" + mac;
			GateWay w = new GateWay();
			w.userId = m.userId;
			w.name = name;
			w.mac = mac;
			String j = JSON.toJSONString(w);
			j = AESUtil.encrypt(j);
			HttpUtils httpUtils = new HttpUtils();
			RequestParams params = new RequestParams();
			params.setHeader("Content-Type", "application/json");
			try {
				params.setBodyEntity(new StringEntity(j, "utf-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			httpUtils.send(HttpRequest.HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/device/add", params,
					new RequestCallBack<String>() {

						@Override
						public void onFailure(HttpException arg0, String arg1) {
							HttpConnection.showToast(getBaseContext(),"网络异常");
						}
						@Override
						public void onSuccess(ResponseInfo<String> arg0) {
							if(arg0.result != null && !"".equals(arg0.result)){
								arg0.result = AESUtil.decrypt(arg0.result);
								GateWay p = JSON.parseObject(arg0.result, GateWay.class);
								if (0 == p.status) {
									mProgressDialog.dismiss();
									Intent it=new Intent(getBaseContext(),WifiConfigFinishActivity.class);
									startActivity(it);
									finish();
								}
							}else{
								HttpConnection.showToast(getBaseContext(),"服务器错误");

							}}
					});
		}
	}

}
